﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using Model;
using System.Data.Entity;
using System.Linq.Expressions;

namespace DAL
{
    public class DataStorage : DbContext
    {
        public DataStorage(DbConnection connection)
            : base(connection, true)
        { }
        public DataStorage(string connectionString)
            : base(connectionString)
        { }

        public DbSet<Area> Areas { get; set; }
        public DbSet<Nation> Nations { get; set; }
        public DbSet<Person> Persons { get; set; }
        public DbSet<PoliticalStatus> PoliticalStatuses { get; set; }
        public DbSet<Profession> Professions { get; set; }
        public DbSet<Relation> Relations { get; set; }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="S"></typeparam>
        /// <param name="pageIndex">页索引，从1开始</param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <param name="whereFunc"></param>
        /// <param name="orderFunc"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public IQueryable<T> GetPagedEntities<T, S>(int pageIndex, int pageSize, out int recordCount, Expression<Func<T, S>> orderFunc, params Expression<Func<T, bool>>[] whereFunc) where T : class
        {
            return GetPagedEntities<T, S>(pageIndex, pageSize, out recordCount, orderFunc, true, whereFunc);
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="S"></typeparam>
        /// <param name="pageIndex">页索引，从1开始</param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <param name="whereFunc"></param>
        /// <param name="orderFunc"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public IQueryable<T> GetPagedEntities<T, S>(int pageIndex, int pageSize, out int recordCount, Expression<Func<T, S>> orderFunc, bool isAsc, params Expression<Func<T, bool>>[] whereFunc) where T : class
        {
            IQueryable<T> query = Set<T>();

            query.Load();
            if (whereFunc != null)
            {
                foreach (var item in whereFunc)
                {
                    query = query.Where(item);
                }
            }

            recordCount = query.Count();
            if (isAsc)
            {
                query = query.OrderBy(orderFunc);
            }
            else
            {
                query = query.OrderByDescending(orderFunc);
            }
            query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return query.AsQueryable();
        }
    }
}
